package logic

import (
	"8-dshop/models"
	"8-dshop/pkg"
	"8-dshop/shoprpc/internal/svc"
	"8-dshop/shoprpc/shoprpc"
	"context"
	"errors"
	"gorm.io/gorm"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *shoprpc.LoginRequest) (*shoprpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User

	if err := user.FindUserByMobile(models.DB, in.Mobile); err != nil {
		return nil, err
	}
	if user.ID == 0 {
		user := &models.User{
			Model:    gorm.Model{},
			Mobile:   in.Mobile,
			Password: pkg.Md5Str(in.Password),
		}
		if err := user.CreatedUser(models.DB); err != nil {
			return nil, err
		}
	} else {
		if pkg.Md5Str(in.Password) != user.Password {
			return nil, errors.New("密码错误请重新输入")
		}
	}
	return &shoprpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
